package com.hdu.handler;


import com.hdu.dao.URLDAO;
import com.hdu.dto.UrlDto;
import com.hdu.service.URLService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hdu.util.RedisConstants.Visit_Count_Key;

@Component
public class SimpleJobHandler {
    private static Logger logger = LoggerFactory.getLogger(SimpleJobHandler.class);

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    URLDAO urldao;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @XxlJob(value = "demoJobHandler",init = "",destroy = "")
    public ReturnT<String> demoJobHandler(String param) throws Exception{
        for (int i = 0; i < 5; i++) {
            XxlJobHelper.log("你好世界"+i);
            TimeUnit.SECONDS.sleep(2);
        }
        return ReturnT.SUCCESS;
    }

    @XxlJob(value = "redisToMysql",init = "",destroy = "")
    public ReturnT<String> redisToMysql(String param) throws Exception{
        //1.定时读取redis中的访问次数
        String counts = (String) redisTemplate.opsForValue().get(Visit_Count_Key + "interview");
//        System.out.println(counts);
//        if(counts)
        //2.读取完后定时更新数据库中的数据
        UrlDto url = new UrlDto("interview", Integer.parseInt(counts == null ? "1" : counts));
        urldao.updateCountByUrl(url);

        return ReturnT.SUCCESS;
    }


}
